import axios from 'axios'
import qsString from 'querystring'
import store from '../store'
let baseUrl = '/api';
//创建请求拦截器
axios.interceptors.request.use((req)=>{
    if(req.url!= baseUrl + '/login'){
       req.headers.authorization = store.getters.getUser.token;
    }
    return req;
});
//创建响应拦截器
axios.interceptors.response.use((res)=>{
    return res.data;
});


//封装get方法
export const get = (url,params={}) =>{
    return new Promise((resolve,reject)=>{
       axios
       .get(baseUrl + url,{
           params,
       })
       .then((res)=>{
           resolve(res);
       })
       .catch((err)=>{
           reject(err);
       });
    });
};



//封装post方法
export const post = (url,params={},isFile=false)=>{
    let data = null;
    if(isFile){
        data = new FormData();
        for(let i in params){
            data.append(i,params[i]);
        }
    }else{
        data = qsString.stringify(params);
    }
    return new Promise((resolve,reject)=>{
        axios
        .post(baseUrl + url,data)
        .then((res)=>{
            resolve(res);
        })
        .catch((err)=>{
            reject(err);
        });
    });
};
